package wong.board.client.util;

import java.util.Iterator;
import java.util.NoSuchElementException;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;

public class IterableJSONObject<V extends JSONValue> implements Iterable<IterableJSONObject.Entry<V>>,
		Iterator<IterableJSONObject.Entry<V>> {

	private JSONObject delegate;
	private Iterator<String> keyIterator;

	public IterableJSONObject(JSONObject delegate) {
		this.delegate = delegate;
		this.keyIterator = this.delegate.keySet().iterator();
	}

	@Override
	public Iterator<IterableJSONObject.Entry<V>> iterator() {
		return this;
	}

	@Override
	public boolean hasNext() {
		if (this.keyIterator != null) {
			if (this.keyIterator.hasNext()) {
				return true;
			} else {
				this.keyIterator = null;
				this.delegate = null;
			}
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public IterableJSONObject.Entry<V> next() {
		if (!hasNext()) {
			throw new NoSuchElementException("no more elements");
		}
		String key = this.keyIterator.next();
		V value = (V) this.delegate.get(key);
		return new IterableJSONObject.Entry<V>(key, value);
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException("remove() is not supported");
	}

	/*
	 * 
	 */

	public static class Entry<Value extends JSONValue> {
		public final String key;
		public final Value value;

		public Entry(String key, Value value) {
			this.key = key;
			this.value = value;
		}
	}

}